import { useAsyncEffect } from '@gnlab/utils/env-react'
import { Modal, Form, message, Input, Switch, Button, Checkbox } from 'antd'
import Link from '@/desktop/components/link'
import services from '@/services'
import type { VoiceToTextSetting } from '@/services/features/voice-to-text'
import './index.module.less'

export { ReactComponent as Icon } from './icon.svg'

export function VoiceToText({ open, onClose }: { open: boolean; onClose: () => void }) {
  return <Modal
    styleName="modal"
    title="语音转文字"
    footer={null}
    width="600px"
    open={open}
    onCancel={onClose}
    maskClosable
    destroyOnClose
  >
    {open ? <Content onClose={onClose} /> : null}
  </Modal>
}

function Content(props: { onClose: () => void }) {
  const { onClose } = props
  const [form] = Form.useForm()

  const [initialValues, setInitialValues] = useState<null | VoiceToTextSetting>(null)
  useAsyncEffect(async () => {
    const data = await services.features.voideToText.load()
    setInitialValues(data)
  }, [])

  const [submitting, setSubmitting] = useState(false)
  const onSubmit = useCallback(
    async (values: VoiceToTextSetting) => {
      setSubmitting(true)
      const resp = await services.features.voideToText.update(values)
      setSubmitting(false)

      if (resp.success) {
        void message.success('配置保存成功')
        onClose()
      } else {
        void message.warning(`配置保存失败：${resp.error}`)
      }
    },
    [onClose],
  )

  if (!initialValues) return <div styleName="loading">载入中...</div>

  const COL_SPAN = 6

  return <Form
    form={form}
    onFinish={onSubmit}
    labelCol={{ span: COL_SPAN }}
    initialValues={initialValues}
  >
    <Form.Item
      label="语音识别"
      name="enable"
      valuePropName="checked"
      extra={
        <div>
          本功能开启后，可自动将收到的语音消息转成文字，并且发送给聊天机器人，注意，本功能对接腾讯云语音识别能力，要使用请先开通&nbsp;
          <Link href="https://cloud.tencent.com/product/asr">腾讯云语音识别服务</Link>
        </div>
      }
    >
      <Switch checkedChildren="开" unCheckedChildren="关" />
    </Form.Item>

    <Form.Item noStyle shouldUpdate>
      {() => {
        const disabled = !(form.getFieldValue('enable') as boolean)
        return <>
          <Form.Item label="SecretId" name="secretId">
            <Input disabled={disabled} />
          </Form.Item>

          <Form.Item label="SecretKey" name="secretKey">
            <Input disabled={disabled} />
          </Form.Item>

          <Form.Item label=" " colon={false} name="forwardToRobot" valuePropName="checked">
            <Checkbox disabled={disabled}>将识别结果交给机器人</Checkbox>
          </Form.Item>
        </>
      }}
    </Form.Item>

    <Form.Item wrapperCol={{ offset: COL_SPAN }}>
      <Button loading={submitting} type="primary" htmlType="submit">
        保存
      </Button>
      <Button styleName="cancel" onClick={onClose}>
        取消
      </Button>
    </Form.Item>
  </Form>
}
